package worker

import (
	"fmt"
	"log"
	"math/rand"
	"sync"
	"time"
)

type DemoClient struct {
	Id int
}

func NewDemoClient(Id int) *DemoClient {
	return &DemoClient{Id: Id}
}

func Work(taskChan chan *WorkTask, routineNum int) chan struct{} {
	//创建客户端连接池，并使用连接池来控制并发数目，避免创建太多客户端连接对服务端造成太大压力
	var clientPool = make(chan *DemoClient, routineNum)
	for i := 0; i < routineNum; i++ {
		clientPool <- NewDemoClient(i)
	}

	var finishChan = make(chan struct{})
	var wg sync.WaitGroup

	for task := range taskChan {
		if task.Id == -1 {
			//任务执行结束
			fmt.Println("所有任务均派发完毕,等待其他协程处理完毕")
			go func() {
				wg.Wait()
				fmt.Println("所有任务均执行完毕")
				finishChan <- struct{}{}
			}()
			break
		}
		wg.Add(1)
		client := <-clientPool
		go func(task *WorkTask) {
			defer func() {
				wg.Done()
				//fmt.Println("go routine finish")
				//执行完成后，吧客户端连接重新送入连接池
				clientPool <- client
			}()
			rt := rand.Intn(3000)
			time.Sleep(time.Millisecond * time.Duration(rt))
			log.Printf("任务 [%d] 处理已完成,使用客户端:[%d]\n", task.Id, client.Id)
		}(task)
	}

	return finishChan
}
